package com.example.yuntiku.dao.impl;

import com.example.yuntiku.dao.BaseDao;
import com.example.yuntiku.dao.ExamanwerDao;
import com.example.yuntiku.entity.Examanwer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ExamanwerDaoImpl extends BaseDao implements ExamanwerDao {
    public int insertExamanwerDao(Examanwer examanwer){
        String sql = "INSERT INTO `yuntiku`.`examanwer` (`testrescordid`,`pagerqustionid`,`chooseanswer`,`rightanswers`) \n" +
                "VALUES(?,?,?,?);";
        return super.executeUpdate(sql,examanwer.getTestrescordid(),examanwer.getPagerqustionid(),examanwer.getChooseanswer(),examanwer.getRightanswers());
    }

    public int selectCorrect(int testrescordid){
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = super.getConnection();
            stmt = conn.prepareStatement("SELECT COUNT(*) AS `correct` FROM `examanwer` WHERE `chooseanswer`=`rightanswers` AND `testrescordid` =?;");
            stmt.setInt(1,testrescordid);
            rs = stmt.executeQuery();
            while (rs.next()){
                int correct;
                correct = rs.getInt("correct");
                return correct;
            }
        }catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            super.closeAll(conn,stmt,rs);
        }
        return 0;
    }
    public List<Examanwer> selectBctim(int testrescordid){
        List<Examanwer> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = super.getConnection();
            stmt = conn.prepareStatement("SELECT `tid`,`testrescordid`,`pagerqustionid`,`chooseanswer`,`rightanswers` FROM `examanwer` WHERE `testrescordid`=?");
            stmt.setInt(1,testrescordid);
            rs = stmt.executeQuery();
            while (rs.next()){
                Examanwer examanwer = new Examanwer();
                examanwer.setTid(rs.getInt("tid"));
                examanwer.setTestrescordid(rs.getInt("testrescordid"));
                examanwer.setPagerqustionid(rs.getInt("pagerqustionid"));
                examanwer.setChooseanswer(rs.getString("chooseanswer"));
                examanwer.setRightanswers(rs.getString("rightanswers"));
                list.add(examanwer);
            }
        }catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            super.closeAll(conn,stmt,rs);
        }
        return list;
    }
}
